package com.grm.util;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * jwt工具类
 *
 * @author gaorimao
 * @date 2022/06/24
 */
@Data
@Component
public class JwtUtil {
    /**
     * JWT 加***
     */
    private static final String SECURITY_KEY = "gaorimao";

    //过期时间
    private static final Long TTL = 60 * 6 *1000L;

    public String createToken(String username){
        JwtBuilder jwtBuilder = Jwts.builder()
            .setSubject(username)  //设置主题 Jwt面向的用户
            .claim("username", username) //自定义属性
            .signWith(SignatureAlgorithm.HS256, SECURITY_KEY);//签名,进行**加密
        return jwtBuilder.compact();
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public String parseToken(String token){
        String username = "";

        try {
            Claims body = (Claims) Jwts.parser().setSigningKey(SECURITY_KEY).parse(token).getBody();
            username = (String) body.get("username");
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
        } catch (MalformedJwtException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return username;
    }
}
